<script setup lang="ts">
import { useAddressApi } from '@/services/address';
import { useAddressStore } from '@/stores/modules/address';
import type { AddressItem } from '@/types/global';
import { onLoad } from '@dcloudio/uni-app';
import { reactive } from 'vue';
import { ref } from 'vue'
const addressStore = useAddressStore()

const addressApi = useAddressApi()
/**
 * 如果有id，那么是修改地址
 * 如果有form，那么是在订单页新增，需要修改一下状态管理当前所选地址
 */
const query = defineProps<{
  id?: string,
  from?: string
}>()
onLoad(() => {
  uni.setNavigationBarTitle({
    title: query.id ? '修改地址' : '新建地址',
  })
  if (query.id) {
    getFormData()
  }
})
// 表单数据
const formData = ref({
  receiver: '',
  contact: '',
  fullLocation: '',
  provinceCode: '',
  cityCode: '',
  countyCode: '',
  address: '',
  isDefault: 0,
})
/**
 * 获取表单数据
 */
const getFormData = async () => {
  const res = await addressApi.getAddressById(query.id!)
  Object.assign(formData.value, res.result)
}
/**
 * 省市县/区切换
 */
const onRegionChange: UniHelper.RegionPickerOnChange = (e) => {
  formData.value.fullLocation = e.detail.value.join(' ')
  const [provinceCode, cityCode, countyCode] = e.detail.code!
  Object.assign(formData.value, { provinceCode, cityCode, countyCode })
}
/**
 * 是否为默认地址切换
 */
const onIsDefaultChange: UniHelper.SwitchOnChange = (e) => {
  formData.value.isDefault = e.detail.value ? 1 : 0
}
/**
 * 新增地址模块
 */
const AddAddress = async () => {
  const res = await addressApi.addAddress(formData.value)
  if (res.result.id) {
    if(query.from === 'goods'){
      console.log('okkkkkk')
      const newAdd = Object.assign(formData.value,{id:res.result.id})
      addressStore.selectedChange(newAdd as unknown as AddressItem)
    }
    uni.showToast({
      icon: 'success',
      title: '新增成功'
    })
  }
}
/**
 * 更新地址
 */
const UpDateAddress = async () => {
  const res = await addressApi.updateAddress(query.id!, formData.value)
  if (res.result.id) {
    uni.showToast({
      icon: 'success',
      title: '修改成功'
    })
  }
}
/**
 * 提交新增或者修改
 */
const onSubmit = async () => {
  try {
    await formRef.value?.validate?.(async (err) => {
      if (!err) {
        if (!query.id) {
          await AddAddress()
        } else {
          await UpDateAddress()
        }
        /**
         * 页面回溯
         */
        setTimeout(() => {
          uni.navigateBack()
        }, 300)
      }
    })
  } catch (error) {
    uni.showToast({
      icon: 'none',
      title: '出错了，请正确填写信息'
    })
  }
}
/**
 * 表单校验
 */
const formRef = ref<UniHelper.UniFormsInstance>()
const rules: UniHelper.UniFormsRules = {
  receiver: {
    rules: [
      {
        required: true,
        errorMessage: '请输入收货人姓名',
      }
    ]
  },
  contact: {
    rules: [
      {
        required: true,
        errorMessage: '请输入手机号码',
      },
      {
        pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
        errorMessage: '请输入正确的手机号码'
      }
    ]
  },
  fullLocation: {
    rules: [
      {
        required: true,
        errorMessage: '请选择地区',
      }
    ]
  },
  address: {
    rules: [
      {
        required: true,
        errorMessage: '请填写详细地址',
      }
    ]
  }
}
</script>

<template>
  <view class="content">
    <uni-forms ref="formRef" :modelValue="formData" :rules="rules">
      <!-- 表单内容 -->
      <uni-forms-item class="form-item" name="receiver">
        <text class="label">姓名</text>
        <input class="input" type="text" placeholder="请填写收货人姓名" v-model="formData.receiver" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="contact">
        <text class="label">联系方式</text>
        <input class="input" type="text" placeholder="请填写收货人手机号" v-model="formData.contact" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="fullLocaltion">
        <text class="label">所在地区</text>
        <picker class="picker" mode="region" @change="onRegionChange" :value="formData.fullLocation.split(' ')">
          <view v-if="formData.fullLocation">{{ formData.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="address">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="formData.address" />
      </uni-forms-item>
      <uni-forms-item name="address">
        <label class="label">设为默认地址</label>
        <switch class="switch" @change="onIsDefaultChange" color="#27ba9b" :checked="formData.isDefault === 1" />
      </uni-forms-item>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @tap="onSubmit">保存并使用</button>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>